package com.woniu.ucenterservice.service.imp;

import com.woniu.enums.ExceptionEnum;
import com.woniu.ucenterservice.dao.UserMapper;
import com.woniu.ucenterservice.exception.LyException;
import com.woniu.ucenterservice.pojo.User;
import com.woniu.ucenterservice.service.UserService;
import com.woniu.ucenterservice.utils.CodecUtils;
import com.woniu.utils.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImp implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

   @Autowired
   private AmqpTemplate amqpTemplate;
//
//    @Autowired
//    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "user:verify:code:";

    @Override
    public Boolean checkData(String data, Integer type) {

        User user = new User();
        //判断校验数据的类型
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw new LyException
                        (ExceptionEnum.INVALID_PARAM);
        }
        return (userMapper.selectByPrimaryKey(user.getUserId()) == null);
    }

//    @Override
//    public void sendVerifyCode(String phone) {
//        String code = NumberUtils.generateCode(6);
//
//        String key = KEY_PREFIX + phone;
//
//        //把验证码放入Redis中，并设置有效期为5min
//        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
//
//        //向mq中发送消息
//        Map<String,String> map = new HashMap<>();
//        map.put("phone", phone);
//        map.put("code", code);
//        amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", map);
//    }

    @Override
    public void register(@Valid User user,String code) {
        user.setUserId(null);
        user.setCreated(new Date());
        String key = KEY_PREFIX + user.getPhone();

        String value = redisTemplate.opsForValue().get(key);

        if (!StringUtils.equals(code, value)) {
            //验证码不匹配
            throw new LyException(ExceptionEnum.VERIFY_CODE_NOT_MATCHING);
        }

        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);

        //生成密码
        String md5Pwd = CodecUtils.md5Hex(user.getPassword(), user.getSalt());

        user.setPassword(md5Pwd);

        //保存到数据库
        int count = userMapper.insert(user);

        if (count != 1) {
            throw new LyException(ExceptionEnum.INVALID_PARAM);
        }

       // 把验证码从Redis中删除
        redisTemplate.delete(key);

    }

    @Override
    public User queryUser(String username, String password) {
//        User record = new User();
//        record.setUsername(username);
//        System.out.println(record);
//        //首先根据用户名查询用户
//        User user = userMapper.selectOne(record.getUsername());
//        System.out.println(user);
//
//        if (user == null) {
//            throw new LyException(ExceptionEnum.USER_NOT_EXIST);
//        }
//
//        //检验密码是否正确
//        if (!StringUtils.equals(CodecUtils.md5Hex(password, user.getSalt()), user.getPassword())) {
//            //密码不正确
//            System.out.println(StringUtils.equals(CodecUtils.md5Hex(password, user.getSalt()), user.getPassword()));
//
//
//            throw new LyException(ExceptionEnum.PASSWORD_NOT_MATCHING);
//        }
        User user = selectUser(username, password);

        return user;
    }

    @Override
    public void fixPassWord(String username, String oldpassword, String newpassword) {
        User user = selectUser(username, oldpassword);
        if (user==null){
            throw new LyException(ExceptionEnum.PASSWORD_NOT_MATCHING);
        }
        //user.setPassword(newpassword);
//        String salt = CodecUtils.generateSalt();
//        user.setSalt(salt);
//
//        //生成密码
//        String md5Pwd = CodecUtils.md5Hex(newpassword, user.getSalt());
//        user.setPassword(md5Pwd);
//        userMapper.updateByPrimaryKey(user);
        updatePwd(user,newpassword);

    }
    public void updatePwd(User user,String pwd){
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);

        //生成密码
        String md5Pwd = CodecUtils.md5Hex(pwd, user.getSalt());
        user.setPassword(md5Pwd);
        userMapper.updateByPrimaryKey(user);

    }

    @Override
    public void isCode(String email,String verCode) {
        String key = KEY_PREFIX + email;

        String value = redisTemplate.opsForValue().get(key);
        if(!StringUtils.equals(verCode,value)){
            throw new LyException(ExceptionEnum.VERIFY_CODE_NOT_MATCHING);
        }
    }

    @Override
    public void findPwd(String username,String pwd) {
//        User record=new User();
//        record.setUsername(username);
        //System.out.println();
        User user=userMapper.selectOne(username);
        System.out.println(pwd);
       updatePwd(user,pwd);

    }

    @Override
    public void sendVerifyCode(String phone) {
        String code = NumberUtils.generateCode(6);

        String key = KEY_PREFIX + phone;

        //把验证码放入Redis中，并设置有效期为5min
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);

        //向mq中发送消息
        Map<String,String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);
        amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", map);
    }

    public User selectUser(String username, String password){
        User record = new User();
        record.setUsername(username);
        System.out.println(record);
        //首先根据用户名查询用户
        User user = userMapper.selectOne(record.getUsername());
        System.out.println(user);

        if (user == null) {
            throw new LyException(ExceptionEnum.USER_NOT_EXIST);
        }

        //检验密码是否正确
        if (!StringUtils.equals(CodecUtils.md5Hex(password, user.getSalt()), user.getPassword())) {
            //密码不正确
            System.out.println(StringUtils.equals(CodecUtils.md5Hex(password, user.getSalt()), user.getPassword()));


            throw new LyException(ExceptionEnum.PASSWORD_NOT_MATCHING);
        }


        return  user;
    }
}
